import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import HotsView from '../views/HotsView.vue'
import LoginView from '../views/LoginView.vue'
import ManageView from '../views/ManageView.vue'
import Detail from '../components/Detail.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    alias: '/',
    name: 'home',
    component: HomeView,
    children: [{
      path: 'detail/:id',
      name: 'detail',
      component: Detail,
    },{
      path: 'detail2',
      name: 'detail2',
      component: Detail,
    }]
  },
  {
    path: '/news',
    name: 'news',
    component: () => import(/* webpackChunkName: "about" */ '../views/NewsView.vue'),
    children: [{
      path: 'tv',
      name: 'tv',
      component:  () => import(/* webpackChunkName: "about" */ '../views/TvView.vue')
    },{
      path: 'film',
      name: 'film',
      component:  () => import(/* webpackChunkName: "about" */ '../views/FilmView.vue')
    }]
  },{
    path: '/hot',
    name: 'hot',
    component: HotsView
  },{
    path: '/login',
    name: 'login',
    component: LoginView,
    beforeEnter: (to,from,next)=>{
      // debugger
      console.log('要访问登录页面啦');
      // 判断是否登录
      let login = localStorage.getItem('login');
      if(login=='true'){
        // next(from.path);
      } else{
        next()
      }
    }
  },{
    path: '/manage',
    name: 'manage',
    component: ManageView
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局前置守卫
router.beforeEach((to,from,next) => {
  // debugger
  console.log('to:',to);
  console.log('from:',from);
  if(to.path=='/login'){
      // 放行
    next();
  } else {
    // 判断是否登录
    let login = localStorage.getItem('login');
    if(login=='true'){
      next();
    } else{
      if(from.path != '/login'){
        next('/login')
      }
    }
  }
})
// 全局后置守卫
router.afterEach((to,from)=>{
  console.log('已成功到达'+to.path);
});

export default router
